package io.rehuo.common.utils.pay;

import com.alibaba.fastjson.JSONObject;
import io.rehuo.common.utils.HttpUtil;
import io.rehuo.modules.app.utils.HttpCommonClientUtils;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

/**
 * hqpay支付工具类
 *
 * @author shiguang on 2022/9/16 14:17
 */
public class HQPayUtils {

    /**
     * 沙箱环境
     */
//    private static final String API_URL = "https://sandbox-merchant.hqpay.vn";

    private static final String API_URL = "https://merchant.hqpay.vn";

    private static final String LOGIN_URL = "/api/login";

    private static final String CREATE_VIRTUAL_CARD = "/api/request-new-card";

    private static final String CREATE_NEW_VA = "/va/create";

    private static final String PAY_URL = "/api/check-inquiry-and-transfer";

    private static final String BANK_URL = "/api/list-banks";

    private static final String redis_key = "hqpay.";

    private static final String TOKEN = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIyIiwianRpIjoiZGU0Nzc5NTllYzk0OWQ5MWEyMzQ0ZTlmZmQ4ZmM1MWNjNmVmYjZiODdhOTZhMjM3NDNhMjFlMGIxZmY4ZDc0NDFkYjFlYmJjOWVmYTdjMWEiLCJpYXQiOjE2NjMzMzMwMDYuMzczMzc4LCJuYmYiOjE2NjMzMzMwMDYuMzczMzgsImV4cCI6MTY5NDg2OTAwNi4zNTc5NjksInN1YiI6IjM5Iiwic2NvcGVzIjpbXX0.Z_G5_9oEuzhZ8qjJ4x_1PUsknup6rUTQ-aV8mrNxxqr34PIlWH67iAHahjelsg3zF_0tW_b8Fn2rhA8xUupCqoPy7vepchoEzwWqlAHCVVdKLNTfxpsEcA13f-XKC3zR2Hgr41GJrdd4WF9lH7w_BXJs8tSerNQn6TEr6mrl4trq99vYexcVNh6p2a97svxAPzdov1hdKjtQ1kqVDLdwKo6rCpWgw8XbfY-anjJKQn-XHl2ewMIhQh6Izg38AElBQyLe3y-kQ8aBVRz5Lmb1krxIandA0FF7l6vJO5y3s85vhsMLKY03jbS1mYURBJxsd2V1SU_sNYrI5dLLIl443EKpvVgUGfN-fe_SN_bLHBPbvQo2SQy2VR9IUiwpWYz3eMBo2eB_XMv4BpiIp_Cxm3J4F2dqeipUyOZp4BiZbhkQ-o22-3OrIBvyGaFSOg2S0QaTdkMxFvdEbFFBLVUY3SxkGl8bQma_N_5MK-A14o8VzyRIRCzgfoJUb3xOa_PVbMDm5-H2SjAAbXWb8gpFQNRaAwFf38DCZ0m6b7BGay9YmXNH3zMZ7Zwq_iuUfJOOdtYJH1GF5jly_rUUyCXFICGc-w8YulzEBra6HG3edmCUDkOMQjrxvxBYzx21KTWFyLt8f-3glCwD2joNwz2p5fpTjezAIktjWQRWV1ossk0";

    private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaSqNyNwISmb4VJX4vk28y5Hed2/JCDdzUKM2xc1460kelEIuy+SFicE4e3I9xMsGOdm/5H3aUiF6EkJ1qqgC2bf7z7oIHbYw9n6CELDiTolHll0b9jJ6BE0bb5uuLAINeybvJR3GJ2q/lKyQYTko7bAoAugXgSRvyRP4aXNuR5QIDAQAB";

    public static void main(String[] args) {

        String data = "{\"id\":\"348\",\"amount\":100000,\"tranDate\":\"2021-08-13 00:00:00\",\"tranId\":\"FT21225STT09\",\"cardId\":null,\"numberOfBeneficiary\":\"NA\",\"fee\":1000,\"description\":\"bentest-TF00000276\",\"account\":\"106000852466\"}";

        String signature = "WDtRUa3XMpdaOhs19nOdk8YU9ioHLy8c789TtbiXMKN2hAycKG5knwEYsgp0wWlyMoVuJr7uCmiV+1f01bawpFgvUZ66G8pUI/rSi2sZIof0uGwVAvwqU9dZPzVi2+gIApfJ6vDJCRwTsTsd2nCVBHNVle9vYEkIhjMdd6HWkjI=";
//        createVirtualCard();
//        pay();
//        byte[] bytes = Base64.decode(signature);

//        login("861460170@qq.com", "12345678o");
//        verifySign(PUBLIC_KEY,data,signature);
        listBank(TOKEN);
    }

    public static PublicKey getPublicKey(String key) {
        try {
            byte[] byteKey = Base64.getDecoder().decode(key);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(byteKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePublic(x509EncodedKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static boolean verifySign(String key, String requestData, String signature) {
        boolean verifySignSuccess = false;
        try {
            PublicKey publicKey = getPublicKey(key);

            Signature verifySign = Signature.getInstance("sha256WithRSA");
            verifySign.initVerify(publicKey);
            verifySign.update(requestData.getBytes());

            verifySignSuccess = verifySign.verify(Base64.getDecoder().decode(signature));
            System.out.println("===验签结果：" + verifySignSuccess);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return verifySignSuccess;
    }


    /**
     * 登录
     *
     * @param email
     * @param password
     * @return
     */
    public static String login(String email, String password) {
        JSONObject json = new JSONObject();
        json.put("email", email);
        json.put("password", password);
//        String result = "";
        String result = HttpUtil.htPost(API_URL + LOGIN_URL, json.toString());
        return result;
    }

    /**
     * 创建虚拟卡
     *
     * @return
     */
    public static String createVirtualCard(String token) {
        String result = HttpUtil.sendGet(API_URL + CREATE_VIRTUAL_CARD, "",token);
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println("返回参数：" + jsonObject.toString());
        return result;
    }

    /**
     * 代付
     * @return
     */
    public static String pay(String bankAccount,String amount,String bankId,String orderNo,String remark,String token) {
        JSONObject json = new JSONObject();
        json.put("ftType", "PAN");
        json.put("numberOfBeneficiary", bankAccount);

        json.put("amount", amount);
        json.put("bankId", bankId);

        json.put("description", remark);
        json.put("order_number", orderNo);

        String result = HttpUtil.post(API_URL + PAY_URL, json.toString(),token);
        System.out.println(result);
        return null;
    }

    /**
     * 创建虚拟账户
     *
     * @param requestId
     * @param token
     * @return
     * @throws Exception
     */
    public static String createNewVa(String requestId,String userName,String companyName, String token) throws Exception {
        HashMap<String, Object> json = new HashMap<>();
        json.put("requestId", requestId);
        json.put("nameRule", "99");
        json.put("numberRule", "01");
        json.put("quantity", 1);
        json.put("description", companyName);
        json.put("returnAccount", true);
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("vaNumber", "");
        map.put("vaName", userName);
        list.add(map);
        json.put("batch", list);
        return HttpCommonClientUtils.executeGethWithBody(API_URL + CREATE_NEW_VA, json, token);
    }

    public static String getInfo(String number,String token) throws Exception {
        JSONObject json = new JSONObject();
        json.put("number", number);
        return HttpCommonClientUtils.executeGethWithBody(API_URL + "/va/info", json, token);
    }

    public static String listBank(String token){
        JSONObject json = new JSONObject();
        String result = HttpUtil.post(API_URL + BANK_URL, json.toString(),token);
        return result;
    }

    public static String payment(String data){
        data = "{\"data\":\"{\\\"id\\\":\\\"348\\\",\\\"amount\\\":100000,\\\"tranDate\\\":\\\"2021-08-13 \n" +
                "00:00:00\\\",\\\"tranId\\\":\\\"FT21225STT09\\\",\\\"cardId\\\":null,\\\"numberOfBeneficiary\\\":\\\"NA\\\",\\\"f\n" +
                "ee\\\":1000,\\\"description\\\":\\\"bentestTF00000276\\\",\\\"account\\\":\\\"106000852466\\\"}\",\"signature\":\"WDtRUa3XMpdaOhs19nOdk8YU9ioHLy8c\n" +
                "789TtbiXMKN2hAycKG5knwEYsgp0wWlyMoVuJr7uCmiV+1f01bawpFgvUZ66G8pUI\\/rSi2sZIof0uGwVAvwqU9dZ\n" +
                "PzVi2+gIApfJ6vDJCRwTsTsd2nCVBHNVle9vYEkIhjMdd6HWkjI=\"}";
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONObject object = jsonObject.getJSONObject("data");
        String id = object.getString("id");
        String amount = object.getString("amount");
        String tranDate = object.getString("tranDate");
        String tranId = object.getString("tranId");
        String cardId = object.getString("cardId");
        String numberOfBeneficiary = object.getString("numberOfBeneficiary");
        String fee = object.getString("fee");
        String description = object.getString("description");
        String account = object.getString("account");
        String signature = object.getString("signature");
        return null;
    }

}
